مشخصات مقاله
آموزش CI With Map-Java Spring
CI با استفاده از Map
مثال تزریق سازنده با استفاده از Map
در این مثال می خواهیم از map به عنوان پاسخی که شامل پاسخ و نام کاربری فرستاده شده است، استفاده کنیم. در اینجا از جفت کلید و مقدار (key-value) به صورت رشته استفاده می کنیم. همانند مثال های قبلی، این مثال نیز برگرفته از فرومی است که" یک سوال می تواند چندین پاسخ داشته باشد" .
Question.java :
این کلاس شامل سه خصیصه، دو سازنده و متد displayInfo() برای نمایش اطلاعات است.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | package com.javatpoint; import java.util.Iterator; import java.util.List; public class Question { private int id; private String name; private List< String> answers; public Question() {} public Question( int id, String name, List< String> answers) { super (); this .id = id; this .name = name; this .answers = answers; } public void displayInfo(){ System.out.println(id+ " " +name); System.out.println( "answers are:" ); Iterator< String> itr=answers.iterator(); while (itr.hasNext()){ System.out.println(itr.next()); } } } <button></button> |
applicationContext.xml:
از خصیصه entry مربوط به map برای تعریف اطلاعات مربوط به کلید و مقدار استفاده شده است.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | < ? xml version = "1.0" encoding = "UTF-8" ?> 6. xsi:schemaLocation="http://www.springframework.org/schema/beans < bean id = "q" class = "com.javatpoint.Question" > < constructor-arg value = "11" >< / constructor-arg > < constructor-arg value = "What is Java?" >< / constructor-arg > < constructor-arg > < map > < entry key = "Java is a Programming Language" value = "Ajay Kumar" >< / entry > < entry key = "Java is a Platform" value = "John Smith" >< / entry > < entry key = "Java is an Island" value = "Raj Kumar" >< / entry > < / map > < / constructor-arg > < / bean > < / beans > < button ></ button > |
Test.java:
این کلاس bean را از فایل applicationContext.xml file می گیرد و متد displayInfo() را فراخوانی می کند.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | package com.javatpoint; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource r= new ClassPathResource( "applicationContext.xml" ); BeanFactory factory= new XmlBeanFactory(r); Question q=(Question)factory.getBean( "q" ); q.displayInfo(); } } <button></button> |